import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'

const request = axios.create({
    baseURL:'/api',
    timeout:600000
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
    // 从localStore获取数据
   let userInfo = localStorage.getItem('userInfo')
    if(userInfo){
        let token = JSON.parse(userInfo).token
        config.headers.token = token
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });



//axios的响应
request.interceptors.response.use(
    (response)=>{
        return response.data
    },
    (error) =>{ //失败回调
        // 401 路由跳转/user/login
        if(error.response.status===401){
            ElMessage.error('登录信息失效，请重新登录')
            router.push('/user/login')
        }else{
            return Promise.reject(error)
        }
       
    }
)

export default request